% AMTH 358 Final - Question 3
% Use the FFT based Circular Convolution to multiply two polynomials
%--------------------------------------------------------------------------------

function [p3] = fft_poly_mult(p1, p2)
  if nargin <2  % print help usage message to console
    usage();
    c = [];
    return;
  end

  len_p1 = length(p1)
  len_p2 = length(p2)
  
  % output vector length must be at least len_p1 + len_p2 -1 long
  % and we then round up to the nearest power of two so that we 
  % can apply the radix-2 FFT based circular convolution to perform
  % the multiplication
  
  len_p3 = 2^ceil(log2(len_p1 + len_p2 -1))
  
  p1_pad = [p1 zeros(1,len_p3-len_p1)];
  p2_pad = [p2 zeros(1,len_p3-len_p2)]; 
    
  p3 = fft_cconv(p1_pad,p2_pad);

function usage()
  disp('Usage: fft_poly_mult <p1> <p2>');
  disp('       The polynomials p1 and p2 are not required to have equal order');
  disp('       Polynomial specifications:');
  disp('           p1(x) = a0 + a1*x + a2*x^2 + ... + aM*x^M');
  disp('           p2(x) = b0 + b1*x + b2*x^2 + ... + bN*x^N');  
  disp('       Arguments based on above polynomials:');
  disp('           p1 = [a0 a1 a2 ... aM]');  
  disp('           p2 = [b0 b1 b2 ... bN]');